package com.example.farmeri.ui.users;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.farmeri.R;
import com.example.farmeri.adapter.MyItemDecoration;
import com.example.farmeri.adapter.UserManagerAdapter;
import com.example.farmeri.presenter.user.IUsersInfoContract;
import com.example.farmeri.presenter.user.UsersInfoPresenter;
import com.example.farmeri.tools.KeyboardUtils;
import com.example.farmeri.ui.base.BaseLinearRecycleViewActivity;
import com.example.farmeri.common.OnExtraClickListener;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用户管理
 */
public class UsersManagerActivity extends BaseLinearRecycleViewActivity<UsersInfoPresenter> implements IUsersInfoContract {

    //取消搜索
    @BindView(R.id.search_cancer)
    TextView searchCancer;

    //搜索
    @BindView(R.id.search_edit)
    EditText searchEdit;

    //搜索结果
    @BindView(R.id.search_recycle)
    RecyclerView searchRecycle;

    //主页面
    @BindView(R.id.users_manager_layout_main)
    ViewGroup mainLayout;

    //搜索页面
    @BindView(R.id.users_manager_layout_search)
    ViewGroup searchLayout;

    //勾选的数目
    @BindView(R.id.sheet_bottom_checkedNum)
    TextView checkedNum;

    //批量删除
    @BindView(R.id.sheet_bottom_del_multi)
    Button multiDel;

    @BindView(R.id.sheet_bottom_container_button)
    LinearLayout container_button;

    UserManagerAdapter mAdapter;

    Integer selectIndex;    //列表中操作控件的位置
    List<String> temp_num = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users_manager);
        ButterKnife.bind(this);

        init();

        //批量删除
        multiDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从最大的开始删除
                Collections.sort(temp_num);
                for (int i=temp_num.size()-1;i>=0;i--){
                    Log.d("TAG", "onClick: position"+temp_num.get(i));
                    mAdapter.notifyItemRemoved(Integer.parseInt(temp_num.get(i)));
                }
                temp_num = new ArrayList<>();
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }
        });


        Button mul_lock = (Button) getLayoutInflater().inflate(R.layout.dialog_button,null);
        mul_lock.setText("批量锁定");
        mul_lock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        container_button.addView(mul_lock);
        //加载更多
        //recyclerView.addOnScrollListener(new BaseRecycleOnScrollListener() {
        //    @Override
        //    public void onLoadMore() {
        //        mAdapter.setLoadState(mAdapter.LOADING);
        //        if (mAdapter.getItemCount() < 20){
        //            // 模拟获取网络数据，延时1s
        //            new Timer().schedule(new TimerTask() {
        //                @Override
        //                public void run() {
        //                    runOnUiThread(new Runnable() {
        //                        @Override
        //                        public void run() {
        //                            for (int i=0;i<10;i++){
        //                                mAdapter.data.add(1);
        //                            }
        //                            mAdapter.setLoadState(mAdapter.LOADING_COMPLETE);
        //                        }
        //                    });
        //                }
        //            }, 1000);
        //        }else {
        //            mAdapter.setLoadState(mAdapter.LOADING_END);
        //        }
        //    }
        //});


    }

    private void init() {
        present = new UsersInfoPresenter(this);
        //设置ToolBar
        initToolBar(R.id.users_manager_toolbar,"用户管理",true);
        //设置底部弹出框
        initBottomBehavior(R.id.sheet_bottom_container);
        //设置底部模态框
        initBottomSheetDialog(R.layout.dialog_model,"确定删除该用户吗");
        //初始化搜索页
        initSearchPager();
        //初始化adapter
        initAdapter();
        //单条数据操作
        initSingleOperate();
    }

    String selectId;

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mAdapter = new UserManagerAdapter(this,R.layout.item_user_manager,getScreeWidth());
        linearRecyclerViewAddData(R.id.users_data_recycle_view,
                mAdapter,
                MyItemDecoration.HIGH_LINE);

        //为列表内的控件(锁定、删除等）设置监听
        mAdapter.setOnExtraClickListener(new OnExtraClickListener() {
            @Override
            public void onLockClick(View v, String  id) {
                Log.e("TAG", "onLockClick: ");
                if (id == null) {
                    return;
                }
                present.lockUser(id);
            }

            @Override
            public void onEditClick(View v, String id) {
                Log.e("TAG", "onEditClick: ");
                Intent intent = new Intent(UsersManagerActivity.this, ViewUserActivity.class);
                intent.putExtra("id",id);
                startActivity(intent);
            }

            @Override
            public void onDelClick(View v, String id) {
                selectId = id;
                bottomSheetDialog.show();
                temp_num.removeAll(temp_num);
            }

            @Override
            public void onChecked(int position) {
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                temp_num.add(String.valueOf(position));
                checkedNum.setText("已勾选"+temp_num.size()+"个");
            }

            @Override
            public void onUnChecked(int position) {
                temp_num.remove(String.valueOf(position));
                checkedNum.setText("已勾选"+temp_num.size()+"个");
                if (temp_num.size() == 0){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        });
    }

    /**
     * 初始化搜索页面
     */
    private void initSearchPager() {
        //搜索监听
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    linearRecyclerViewAddData(R.id.search_recycle,
                            mAdapter,
                            MyItemDecoration.HIGH_LINE);
                    return true;
                }
                return false;
            }
        });

        //取消搜索
        searchCancer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchLayout.setVisibility(View.GONE);
                mainLayout.setVisibility(View.VISIBLE);
                searchRecycle.setAdapter(null);
                KeyboardUtils.hideKeyboard(searchEdit);
            }
        });
    }


    TextView confirm;   //单选确定
    TextView cancer;    //单选返回
    protected void initSingleOperate() {
        //单选删除确定
        confirm = dialogView.findViewById(R.id.dialog_bottom_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectId == null){
                    return;
                }
                present.deleteUser(selectId);
                bottomSheetDialog.cancel();
            }
        });
        //单选删除取消
        cancer = dialogView.findViewById(R.id.dialog_bottom_cancer);
        cancer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.cancel();
            }
        });
    }

    /**
     * 设置ToolBar内容
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu,menu);
//        //添加搜索按钮
//        MenuItem searchAction = menu.add("搜索");
//        searchAction.setIcon(R.drawable.ic_search_white_24dp);
//        searchAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        searchAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                mainLayout.setVisibility(View.GONE);
//                searchLayout.setVisibility(View.VISIBLE);
//                //设置输入内容为空
//                searchEdit.setText("");
//                //输入框获取焦点弹出软键盘
//                KeyboardUtils.showKeyboard(searchEdit);
//                return true;
//            }
//        });
//
//        //添加操作按钮
//        MenuItem addAction = menu.add("添加");
//        addAction.setIcon(R.drawable.ic_add_white_24dp);
//        addAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
//        addAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                startActivity(new Intent(UsersManagerActivity.this, AddUsersActivity.class));
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onLockUserSuccess() {
        //mAdapter.notifyDataSetChanged();
        showToast("数据更新");
        mAdapter.init();
    }

    @Override
    public void onDeleteUserSuccess() {
        //mAdapter.notifyDataSetChanged();
        mAdapter.init();
        showToast("数据删除");
    }

    @Override
    public void onError(String msg) {
        showMessage(msg);
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }
}
